/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.workingtimemanager.urb;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import de.workingtimemanager.urb.db.DatabaseHandler;
import de.workingtimemanager.urb.entities.User;
import java.util.Vector;

/**
 *
 * @author CK05102
 */
public class ViewUsersActivity extends Activity {

    Context context;
    String dbname;
    DatabaseHandler db;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // ToDo add your GUI initialization code here
        setContentView(R.layout.viewusers);
        db = new DatabaseHandler();
        context = this;
        createView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        createView();
    }

    private void createView() {
        LinearLayout layout = (LinearLayout) findViewById(R.id.viewusers_userbuttons_layout);
        layout.removeAllViewsInLayout();

        try {
            db.open(context);
            //reset active user
            User oldActive = db.getActiveUser();
            if (oldActive != null) {
                oldActive.setActive(false);
            }
            db.insert(oldActive);
            Vector<User> users = db.getAllUsers();

            for (int i = 0; i < users.size(); i++) {
                final Button button = new Button(this);
                button.setText(users.elementAt(i).getUSERNAME());
                layout.addView(button);

                button.setOnClickListener(new OnClickListener() {

                    public void onClick(View v) {
                        try {
                            db.open(context);
                            User activeUser = db.getUser(button.getText().toString());
                            activeUser.setActive(true);
                            db.insert(activeUser);
                        } finally {
                            db.close();
                        }
                        startActivity(new Intent(context,
                                ViewProjectsActivity.class));
                    }
                });
            }
        } finally {
            db.close();
        }

        final Button createButton = (Button) findViewById(R.id.viewusers_create_button);
        createButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                startActivity(new Intent(context, CreateUserActivity.class));
            }
        });

    }
}
